package cn.wgx.commons.util;

import com.alibaba.fastjson.JSONObject;
import com.drew.imaging.FileType;
import com.drew.imaging.ImageMetadataReader;
import com.drew.imaging.ImageProcessingException;
import com.drew.metadata.Directory;
import com.drew.metadata.Metadata;
import com.drew.metadata.Tag;
import net.coobird.thumbnailator.Thumbnails;
import net.coobird.thumbnailator.geometry.Positions;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 图片压缩(缩略图)
 */
public class ThumbnailsUtils {

    public static float ZOO_MIN_WIDTH = 1000f;

    public static String DEFAULT_WATERMARK = "";

    public static Font DEFAULT_FONT = new Font("宋体", Font.BOLD + Font.ITALIC, 50);

    public static Color DEFAULT_COLOR = new Color(247, 223, 61);

    public static int DEFAULT_WATER_WIDTH = 200;

    public static int DEFAULT_WATER_HEIGHT = 200;

    public static BufferedImage DEAFULT_WATERMARK;


    /**
     * 生成缩略图
     * @param bufferedImage
     * @return
     * @throws IOException
     */
    public static BufferedImage getThumbnails(BufferedImage bufferedImage, String ext) throws IOException {
        float scale = ZOO_MIN_WIDTH / new Long(bufferedImage.getWidth());
        if(scale > 1f){
            scale = 1f;
        }
        return Thumbnails.of(bufferedImage).scale(scale).outputQuality(0.2f).outputFormat(ext).asBufferedImage();
    }

    public static File[] waterMark(File[] file){
        if(file != null){
            int n = file.length;
            File[] newFiles = new File[n];
            for(int i=0;i<n;i++){
                try {
                    File f = file[i];
                    String fileDir = f.getParent() + "/";
                    String ext = StringUtils.getFileExt(f.getName());
                    BufferedImage bufferedImage = ImageIO.read(f);
                    BufferedImage bufferedImage1 = waterMark(bufferedImage,ext);
                    File newFile = new File(fileDir + UUID.randomUUID() + "." + ext);
                    ImageIO.write(bufferedImage1, ext, newFile);
                    newFiles[i] = newFile;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return newFiles;
        }
        return null;
    }


    /**
     * 图片加水印
     * @param bufferedImage
     * @return
     * @throws IOException
     */
    public static BufferedImage waterMark(BufferedImage bufferedImage, String ext) throws IOException {
        return Thumbnails.of(bufferedImage).scale(1f).outputFormat(ext).
                watermark(Positions.BOTTOM_RIGHT, getDefaultWaterMark(), 0.4f).asBufferedImage();
    }

    public static BufferedImage getDefaultWaterMark() {
        if (DEAFULT_WATERMARK == null)
            DEAFULT_WATERMARK = ThumbnailsUtils.getWaterMark(DEFAULT_WATERMARK, DEFAULT_FONT, DEFAULT_COLOR, DEFAULT_WATER_WIDTH, DEFAULT_WATER_HEIGHT);
        return DEAFULT_WATERMARK;
    }
    public static BufferedImage getWaterMark(String pressText,
                                             Font font,
                                             Color color,
                                             int width, int height){
        BufferedImage image = new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();
        image = g.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
        g.dispose();
        g = image.createGraphics();
        g.setColor(color);
        g.setFont(font);
        g.drawString(pressText,0,font.getSize());
        g.dispose();
        return image;
    }

    /**
     * 获取图像MetaData
     *
     * @param jpegFile
     * @return
     * @throws ImageProcessingException
     * @throws IOException
     */
    public static JSONObject getMetaData(File jpegFile) throws ImageProcessingException, IOException {
        Metadata metadata = ImageMetadataReader.readMetadata(jpegFile);
        JSONObject map = new JSONObject();
        for (Directory directory : metadata.getDirectories()) {
            JSONObject o = new JSONObject();
            for (Tag tag : directory.getTags()) {
                o.put(tag.getTagName(), tag.getDescription());
            }
            map.put(directory.getName(), o);
        }
        return map;
    }

    /**
     * 获取图像MetaData
     *
     * @param jpegFile
     * @param ext
     * @return
     * @throws ImageProcessingException
     * @throws IOException
     */
    public static JSONObject getMetaData(byte[] jpegFile, String ext, String fileName) throws ImageProcessingException, IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(jpegFile);
        Metadata metadata = ImageMetadataReader.readMetadata(byteArrayInputStream, new Long(jpegFile.length), getFileTypeByExt(ext));
        JSONObject map = new JSONObject();
        for (Directory directory : metadata.getDirectories()) {
            JSONObject o = new JSONObject();
            for (Tag tag : directory.getTags()) {
                o.put(tag.getTagName(), tag.getDescription());
            }
            map.put(directory.getName(), o);
        }
        map.put("oriFilename",fileName);
        return map;
    }
    /**
     * 根据图片缓存获取byte[]
     *
     * @param bufferedImage
     * @param ext
     * @return
     * @throws IOException
     */
    public static byte[] getBytesByImageBuffer(BufferedImage bufferedImage, String ext) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(bufferedImage, ext, byteArrayOutputStream);
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 根据文件获取图片缓存对象
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static BufferedImage getBufferedImageByFile(File file) throws IOException {
        return ImageIO.read(file);
    }

    /**
     * 根据byte[]获取BufferedImage
     * @param file
     * @return
     * @throws IOException
     */
    public static BufferedImage getBufferedImageByFile(byte[] file) throws IOException {
        return ImageIO.read(new ByteArrayInputStream(file));
    }

    public static String getImageSize(BufferedImage bufferedImage){
        return bufferedImage.getWidth() +  " x " + bufferedImage.getHeight();
    }

    public static FileType getFileTypeByExt(String ext) {
        switch (ext) {
            case IMAGE_TYPE_JPG:
                return FileType.Jpeg;
            case IMAGE_TYPE_JPEG:
                return FileType.Jpeg;
            case IMAGE_TYPE_GIF:
                return FileType.Gif;
            case IMAGE_TYPE_BMP:
                return FileType.Bmp;
            case IMAGE_TYPE_PNG:
                return FileType.Png;
            case IMAGE_TYPE_PSD:
                return FileType.Psd;
            default:
                return FileType.Jpeg;
        }
    }

    /**
     * 几种常见的图片格式
     */
    public static final String IMAGE_TYPE_GIF = "gif";// 图形交换格式
    public static final String IMAGE_TYPE_JPG = "jpg";// 联合照片专家组
    public static final String IMAGE_TYPE_JPEG = "jpeg";// 联合照片专家组
    public static final String IMAGE_TYPE_BMP = "bmp";// 英文Bitmap（位图）的简写，它是Windows操作系统中的标准图像文件格式
    public static final String IMAGE_TYPE_PNG = "png";// 可移植网络图形
    public static final String IMAGE_TYPE_PSD = "psd";// Photoshop的专用格式Photoshop

}
